package test;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Date;
import java.util.List;

import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class LsdaDBMoniterListener implements JobListener {
	
	private static Logger _log = LoggerFactory.getLogger(LsdaDBMoniterListener.class);
    
    public String getName() {
        return "LsdaDBMoniterListener to fetch tasks";
    }

    public void jobToBeExecuted(JobExecutionContext inContext) {
        _log.info("LsdaDBMoniterListener says: Job Is about to be executed.");
    }

    public void jobExecutionVetoed(JobExecutionContext inContext) {
        _log.info("LsdaDBMoniterListener says: Job Execution was vetoed.");
    }

    public void jobWasExecuted(JobExecutionContext inContext,
            JobExecutionException inException) {
        _log.info("LsdaDBMoniterListener says: Job was executed.");
        
        JobDataMap dataMap = inContext.getJobDetail().getJobDataMap();
        int count = dataMap.getInt("count");
        
        if(count > 1){
        	List<LsdaTask> tasks = LsdaTask.fetchNewTasksFromDB();
        	for(LsdaTask task : tasks){
        		// define the job and tie it to our HelloJob class
    			JobDetail job = newJob(LsdaTask.class)
    					.withIdentity(task.getName(), "group"+task.getGroupId())
    					.usingJobData("taskid", task.getId())
    					.build();
    			
    			// Trigger the job to run now, and then repeat every 40 seconds
    			CronTrigger trigger = newTrigger()
    					.withIdentity("trigger"+task.getId(), "group"+task.getGroupId())
    					.withSchedule(cronSchedule(task.getCronExpr()))
    					.forJob(task.getName(), "group"+task.getGroupId())
    					.build();

    			// Tell quartz to schedule the job using our trigger
    			Date ft = null;
				try {
					ft = inContext.getScheduler().scheduleJob(job, trigger);
					_log.info(job.getKey() + " has been scheduled to run at: " + ft
	    	                + " and repeat based on expression: "
	    	                + trigger.getCronExpression());
				} catch (SchedulerException e) {
					_log.warn("Unable to schedule fetched task " + task.getName() + " !");
					e.printStackTrace();
				}
			}
        }
    }
}
